/*
 * Copyright 2007-2010 Jeremy Brown.
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @author <a href="http://jeremy-brown.com">Jeremy Brown</a>
 */


package groovy.prefuse.factory

import groovy.util.AbstractFactory;
import groovy.util.FactoryBuilderSupport;

import prefuse.data.expression.*

public class PredicateFactory extends AbstractFactory
{
	private Class klass

	public PredicateFactory()
	{
	}
	
	public PredicateFactory(Class klass)
	{
		this.klass = klass
	}

	boolean isLeaf()
	{
		return false
	}
	    
    public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException
	{
		builder.context.put("name", attributes.remove("name"))

		if(value == null && attributes.action)
		{
			value = attributes.remove("predicate")
		}
		
		if(value instanceof Predicate)
		{
			return value
		}

		/*
		def buildClass
		if(klass)
		{
			buildClass = klass
		}
		else if(value instanceof Class)
		{
			buildClass = value
			value = null
		}

		
		def action = null
		
		if(buildClass instanceof Class && Predicate.isAssignableFrom(buildClass))
		{
			if(AndPredicate.equals(buildClass))
			{
				predicate = new AndPredicate()
			}
			else if(OrPredicate.equals(buildClass))
			{
				predicate = new OrPredicate()
			}
			else
			{
				//Try to instantiate the Predicate with a no-parameter-constructor
				predicate = buildClass.newInstance()
			}
		}
		*/
		return action
	}
    
	public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object child) 
	{
		addNodeToParent(builder, parent, child)
    }
	
	public void addNodeToParent(FactoryBuilderSupport builder, Object parent, Object child)
	{
		if(parent instanceof CompositePredicate)
		{
			parent.add(child)
		}
		else
		{
			//Try to use the setPredicate method on the parent (it may not exist) - if it doesn't, there is no parent
			try
			{
				parent.setPredicate(child)
			}
			catch(Exception e){}
		}
	}
}
